<template>
  <div class="app-container">
    <div class="content">
      <h3 style="margin-bottom: 30px">1.{{ settingTitle }}基本信息</h3>
      <jblForm
        :ref-name.sync="formRef"
        :form.sync="form"
        :value-data.sync="form.valueData"
      >
        <template v-slot:form-logoImg>
          <el-upload
            class="avatar-uploader"
            action="#"
            accept=".jpg,.jpeg,.png,.JPG,.JPEG"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :http-request="businessLogo"
          >
            <img
              v-if="form.valueData.logoImg"
              :src="form.valueData.logoImg"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </template>
        <template v-slot:form-doBusinessTime>
          <el-row v-for="(weekItem, index) in weekData" :key="index">
            <el-select
              style="width: 100px"
              size="small"
              v-model="weekItem.weekStart"
              placeholder="请选择开始日期"
            >
              <el-option
                v-for="item in weekList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <span style="color: #606266">至</span>
            <el-select
              style="width: 100px"
              size="small"
              v-model="weekItem.weekEnd"
              placeholder="请选择结束日期"
            >
              <el-option
                v-for="item in weekList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <el-time-picker
              size="small"
              is-range
              v-model="weekItem.startEndTime"
              format="HH : mm"
              value-format="timestamp"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间范围"
            >
            </el-time-picker>
            <el-button
              v-show="index + 1 === weekData.length"
              size="small"
              icon="el-icon-plus"
              circle
              @click="addDoBusinessTime"
            ></el-button>
            <el-button
              v-show="index + 1 !== weekData.length"
              size="small"
              icon="el-icon-minus"
              circle
              @click="romoveDoBusinessTime(index)"
            ></el-button>
          </el-row>
        </template>
      </jblForm>

      <h3 style="margin: 40px 0 30px">2.{{ settingTitle }}属性设置</h3>
      <jblForm
        :ref-name.sync="schoolFormFormRef"
        :form.sync="schoolForm"
        :value-data.sync="schoolForm.valueData"
      >
        <template v-slot:form-synopsisImg>
          <el-row type="flex">
            <draggable
              style="display: flex"
              v-model="schoolForm.valueData.synopsisImg"
              :options="{ animation: 500 }"
            >
              <div
                v-for="(item, index) in schoolForm.valueData.synopsisImg"
                :key="index"
                class="img-upload"
              >
                <div v-if="index === 0" class="zt">主图</div>
                <img
                  style="width: 100%; height: 100%"
                  fit="contain"
                  :src="item"
                />
                <div class="img-upload-shaow">
                  <i class="el-icon-delete" @click="removeImg(index)" />
                </div>
              </div>
            </draggable>
            <el-upload
              class="avatar-uploader"
              action="#"
              :class="{ disabled: avatarIsMax }"
              :show-file-list="false"
              :http-request="handleUploda"
              :before-upload="beforeUpload"
              :on-exceed="onExceed"
            >
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-row>
        </template>
        <template v-slot:form-detail>
          <el-row>
            <el-select
              size="small"
              style="width: 160px"
              v-model="schoolForm.province"
              placeholder="请选择省份"
              @change="provinceChange"
            >
              <el-option
                v-for="item in addressOptions.province"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <el-select
              size="small"
              style="width: 160px"
              v-model="schoolForm.city"
              placeholder="请选择城市"
              @change="cityChange"
            >
              <el-option
                v-for="item in addressOptions.city"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <el-select
              size="small"
              style="width: 160px"
              v-model="schoolForm.area"
              placeholder="请选择市区"
              @change="areaChange"
            >
              <el-option
                v-for="item in addressOptions.area"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <el-select
              size="small"
              style="width: 160px"
              v-model="schoolForm.street"
              placeholder="请选择街道( 可空 )"
              @change="streetChange"
            >
              <el-option
                v-for="item in addressOptions.street"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-row>
          <el-row>
            <el-input
              size="mini"
              style="width: 390px"
              v-model="schoolForm.valueData.detail"
              placeholder="点击获取定位地址"
              @focus="openTmap"
            ></el-input>
          </el-row>
        </template>
        <template v-slot:form-categoryIds>
          <el-row>
            <el-checkbox
              v-model="schoolForm.valueData.checked"
              @change="useCargey"
              >应用总校开设的分类</el-checkbox
            >
          </el-row>
          <el-row>
            <el-tabs v-model="activeName" @tab-click="handleClickCategory">
              <el-tab-pane
                v-for="item in categoryAllList"
                :key="item.id"
                :label="item.name"
                :name="item.id"
              >
                <!-- <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll[index]" @change="handleCheckAllChange">全选</el-checkbox> -->
                <div style="margin: 15px 0"></div>
                <el-checkbox-group
                  v-model="schoolForm.valueData.categoryIds"
                  @change="handleCheckedCitiesChange"
                >
                  <el-checkbox
                    v-for="categories in item.categories"
                    :label="categories.id"
                    :key="categories.id"
                    >{{ categories.name }}</el-checkbox
                  >
                </el-checkbox-group>
              </el-tab-pane>
            </el-tabs>
          </el-row>
        </template>
      </jblForm>
      <el-row type="flex" justify="center">
        <el-button @click="closeEdit">取消</el-button>
        <el-button :loading="submitLoading" type="primary" @click="submit">保存</el-button>
      </el-row>
    </div>
    <el-dialog
      title="选择地址"
      :visible.sync="addressOptions.dialog"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      @opened="addressDialog"
      @close="1"
      width="750px"
    >
      <div ref="mapArry" style="width: 100%; height: 600px">
        <iframe
          id="mapPage"
          width="100%"
          height="100%"
          frameborder="0"
          src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=R6GBZ-ZPH6S-F6XOL-6OEWC-VZNX2-GKFMY&referer=myapp"
        ></iframe>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addressOptions.dialog = false">取 消</el-button>
        <el-button type="primary" @click="addressOptions.dialog = false"
          >关闭</el-button
        >
      </div>
    </el-dialog>
    <!-- 图片裁剪 -->
    <el-dialog
      title="裁剪图片"
      :visible.sync="cropper.dialog"
      width="800px"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      @close="cropperClose"
    >
      <div
        class="vue-cropper"
        :style="{ width: cropper.width, height: cropper.height }"
      >
        <VueCropper
          ref="cropper"
          :img="option.img"
          :outputSize="option.size"
          :outputType="option.outputType"
          :info="true"
          :full="option.full"
          :canMove="option.canMove"
          :canMoveBox="option.canMoveBox"
          :original="option.original"
          :autoCrop="option.autoCrop"
          :fixed="option.fixed"
          :fixedNumber="option.fixedNumber"
          :centerBox="option.centerBox"
          :infoTrue="option.infoTrue"
          :fixedBox="option.fixedBox"
        ></VueCropper>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cropper.dialog = false">取 消</el-button>
        <el-button type="primary" @click="confirmCropper">确定裁剪</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import jblForm from "@/components/JblForm";
import { VueCropper } from "vue-cropper";
import draggable from "vuedraggable";

import {
  provinceList,
  cityList,
  areaList,
  streetList,
  getCategoryAll,
} from "@/api/common";
import {
  merchantType,
  getAllLabels,
  getById,
  updateById,
} from "@/api/mechanism";

export default {
  name: "Home",
  components: {
    jblForm,
    VueCropper,
    draggable,
  },
  data() {
    var validatePhone = (rule, value, callback) => {
      if (!/^1[3456789]\d{9}$/.test(value)) {
        callback(new Error("请输入正确的手机号码"));
      } else {
        callback();
      }
    };
    return {
      settingTitle:'',
      avatarIsMax: false,
      submitLoading: false,
      formRef: {},
      schoolFormFormRef: {},
      superAdminFormRef: {},
      isLogoImg: true,
      // 裁剪组件的基础配置option
      option: {
        mode: "cover", // 图片默认渲染方式
        img: "", // 裁剪图片的地址
        info: true, // 裁剪框的大小信息
        outputSize: 1, // 裁剪生成图片的质量
        outputType: "jpeg", // 裁剪生成图片的格式
        canScale: true, // 图片是否允许滚轮缩放
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 750, // 默认生成截图框宽度
        autoCropHeight: 560, // 默认生成截图框高度
        fixedBox: false, // 固定截图框大小 不允许改变
        fixed: true, // 是否开启截图框宽高固定比例
        fixedNumber: [750, 560], // 截图框的宽高比例
        full: false, // 是否输出原图比例的截图
        canMoveBox: true, // 截图框能否拖动
        original: false, // 上传图片按照原始比例渲染
        centerBox: true, // 截图框是否被限制在图片里面
        infoTrue: true, // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
      },
      cropper: {
        dialog: false,
        src:
          "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1592979325958&di=95cd2f2b6fc195bab6e89fe3fb3fe629&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fblog%2F201306%2F29%2F20130629033734_XuJ5V.jpeg",
        width: "750px",
        height: "560px",
        aspectRatio: 1,
        fileBlob: {},
      },
      parentId: "", // 总校id
      activeName: "1",
      categoryAllList: [], // 所有分类集合
      checkAll: [],
      isIndeterminate: true,
      checkedCities: [],
      categorySonItem: [], // 子分类
      weekData: [
        {
          weekStart: null,
          weekEnd: null,
          startEndTime: null,
        },
      ],
      weekList: [
        {
          value: 1,
          label: "每周一",
        },
        {
          value: 2,
          label: "每周二",
        },
        {
          value: 3,
          label: "每周三",
        },
        {
          value: 4,
          label: "每周四",
        },
        {
          value: 5,
          label: "每周五",
        },
        {
          value: 6,
          label: "每周六",
        },
        {
          value: 0,
          label: "每周日",
        },
      ],
      form: {
        file: {},
        data: [
          {
            type: "slot",
            prop: "logoImg",
            labelWidth: "120px",
            show: () => {},
            label: "机构logo",
            rules: [
              { required: true, message: "请上传机构logo", trigger: "blur" },
            ],
          },
          {
            type: "input",
            labelWidth: "120px",
            prop: "name",
            label: "机构名称",
            placeholder: "请输入机构名称",
            rules: [
              { required: true, message: "请输入机构名称", trigger: "change" },
              {
                min: 1,
                max: 40,
                message: "长度在 1 到 40 个字符",
                trigger: "blur",
              },
            ],
          },
          {
            type: "ymdDatetime",
            valueFormat: "timestamp",
            labelWidth: "120px",
            prop: "foundTime",
            label: "开业日期",
            placeholder: "请填写开业日期",
            // rules: [
            //   {
            //     required: true,
            //     message: "请选择时间",
            //     trigger: "blur",
            //   },
            // ],
          },
          {
            type: "slot",
            prop: "doBusinessTime",
            show: () => {},
            labelWidth: "120px",
            label: "营业时间",
          },
          {
            type: "inputNumber",
            labelWidth: "120px",
            prop: "serverPhone",
            label: "服务电话",
            placeholder: "请输入机构服务电话",
            rules: [
              { required: true, validator: validatePhone, trigger: "blur" },
            ],
          },
          {
            type: "tinymce",
            labelWidth: "120px",
            height: 400,
            prop: "synopsis",
            label: "机构简介",
            placeholder: "请填写机构简介",
            rules: [
              {
                required: true,
                message: "请填写机构简介",
                trigger: "blur",
              },
            ],
          },
        ],
        valueData: {
          src:
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1592979325958&di=95cd2f2b6fc195bab6e89fe3fb3fe629&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fblog%2F201306%2F29%2F20130629033734_XuJ5V.jpeg",
          logoImg: "",
          detail: "",
        },
      },
      isMax: false,
      schoolForm: {
        dialog: false,
        topTypeIndex: "0",
        allTypeList: [],
        topTypeList: [],
        childrenType: [],
        chooseTypes: [],
        checkTypeAll: false,
        isTypeIndeterminate: true,
        AllLabels: [],
        province: "", // 省
        city: "",
        area: "",
        street: "",
        data: [
          {
            type: "slot",
            prop: "synopsisImg",
            show: () => {},
            labelWidth: "140px",
            label: "机构轮播宣传图",
            rules: [
              {
                required: true,
                message: "请最少上传一张图片",
                trigger: "blur",
              },
            ],
          },
          {
            type: "slot",
            prop: "detail",
            show: () => {},
            labelWidth: "140px",
            label: "定位地址",
            rules: [
              { required: true, message: "地址不能为空", trigger: "blur" },
            ],
          },
          {
            type: "input",
            labelWidth: "140px",
            prop: "addressRemarks",
            label: "详细地址",
            placeholder: "请输入详细地址",
            rules: [
              { required: true, message: "请输入详细地址", trigger: "blur" },
            ],
          },
          {
            type: "slot",
            prop: "categoryIds",
            show: () => {},
            labelWidth: "140px",
            label: "课程开设分类",
            rules: [
              { required: true, message: "课程开设分类", trigger: "change" },
            ],
          },
          {
            type: "checkboxGroup",
            labelWidth: "140px",
            prop: "labels",
            label: "标签选择",
            checkboxGroup: () => {
              return this.schoolForm.AllLabels;
            },
            rules: [
              { required: true, message: "请选择标签", trigger: "change" },
            ],
          },
        ],
        valueData: {
          imageUrl: "",
          detail: "",
          latLng: "",
          categoryIds: [],
          categoryNames: [],
          addressValue: "",
          province: "", // 省
          city: "", // 市
          region: "", // 区
          town: "", // 街道
          lat: "",
          lng: "",
          addressRemarks: "",
          checked: false,
          activeName: "first",
          labels: [],
          synopsisImg: [],
        },
      },
      addressOptions: {
        dialog: false,
        province: [], // 省
        city: [],
        area: [],
        street: [],
        searchAdress: "",
        options: [],
        lat: "",
        lng: "",
        currentCity: "",
      },
      superAdminForm: {
        data: [
          {
            type: "input",
            labelWidth: "120px",
            prop: "principalName",
            label: "校长（负责人）",
            placeholder: "请输入姓名",
            rules: [{ required: true, message: "请输入姓名", trigger: "blur" }],
          },
          {
            type: "inputNumber",
            labelWidth: "120px",
            prop: "principalPhone",
            label: "负责人电话",
            placeholder: "请输入负责人电话",
            rules: [
              {
                required: true,
                message: "请输入负责人电话",
                trigger: "blur",
              },
              { validator: validatePhone, trigger: "change" },
            ],
          },
          {
            type: "input",
            labelWidth: "120px",
            disabled: true,
            prop: "serverPhone",
            label: "登录账号",
            placeholder: "登录账号为负责人电话",
          },
          {
            type: "input",
            disabled: true,
            labelWidth: "120px",
            prop: "password",
            label: "初始密码",
            placeholder: "请输入密码",
          },
        ],
        valueData: {
          password: "JBL123456",
        },
      },
    };
  },
  computed: {
    ...mapGetters(["roles"]),
  },
  watch: {
    "schoolForm.valueData.synopsisImg"(val) {
      this.avatarIsMax = val.length >= 6;
    },
  },
  created() {
    this.settingTitle = this.$route.query.title
    this.getData();
  },
  mounted() {
    const that = this;
    // 为了防止火狐浏览器拖拽的时候以新标签打开
    document.body.ondrop = function (event) {
      event.preventDefault();
      event.stopPropagation();
    };
    window.addEventListener(
      "message",
      function (event) {
        // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
        var loc = event.data;
        if (loc && loc.module == "locationPicker") {
          // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
          // console.log('location', loc)
          that.schoolForm.valueData.lat = loc.latlng.lat;
          that.schoolForm.valueData.lng = loc.latlng.lng;
          that.schoolForm.valueData.detail = `${loc.poiaddress}${loc.poiname}`;
        }
      },
      false
    );
    this.getLocation();
  },
  methods: {
    addDoBusinessTime() {
      this.weekData.push({
        weekStart: 1,
        weekEnd: 1,
        startEndTime: null,
      });
    },
    romoveDoBusinessTime(index) {
      this.weekData.splice(index, 1);
    },
    businessLogo(res, fileList) {
      this.isLogoImg = true;
      this.cropper = {
        dialog: true,
        src: "",
        width: "400px",
        height: "400px",
      };
      this.option.fixedNumber = [1, 1];
      // this.cropper.src = URL.createObjectURL(res.file)
      this.option.img = URL.createObjectURL(res.file);
    },
    // 裁剪后上传
    fileBlob(blod) {
      const raw = {
        raw: blod,
        name: new Date().valueOf(),
      };
      this.uploadImgToOss(raw)
        .then((response) => {
          const { imgUrl } = response;
          if (this.isLogoImg) {
            this.form.valueData.logoImg = imgUrl;
          } else {
            this.schoolForm.valueData.synopsisImg.push(imgUrl);
          }
        })
        .finally(() => {
          this.cropper.dialog = false;
        });
    },
    cropperClose() {
      this.cropper.src = "";
    },
    handleAvatarSuccess(res, file) {
      // this.form.valueData.imageUrl = URL.createObjectURL(file.raw)
      // this.form.valueData.imageUrl = file.raw
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG、PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    onExceed() {
      this.$message({
        message: "最多上传6张图片",
        type: "warning",
      });
    },
    handleUploda(res, fileList) {
      this.isLogoImg = false;
      this.cropper = {
        dialog: true,
        src: "",
        width: "750px",
        height: "560px",
      };
      this.option.fixedNumber = [750, 560];
      // this.cropper.src = URL.createObjectURL(res.file)
      this.option.img = URL.createObjectURL(res.file);
    },
    // 确定裁剪
    confirmCropper() {
      this.$refs.cropper.getCropBlob((data) => {
        // var fileName = 'goods' + this.fileinfo.uid
        const raw = {
          raw: data,
          name: new Date().valueOf(),
        };
        this.uploadImgToOss(raw)
          .then((response) => {
            const { imgUrl } = response;
            if (this.isLogoImg) {
              this.form.valueData.logoImg = imgUrl;
            } else {
              this.schoolForm.valueData.synopsisImg.push(imgUrl);
            }
          })
          .finally(() => {
            this.cropper.dialog = false;
          });
      });
    },
    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG、PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 删除相册图片
    removeImg(index) {
      this.schoolForm.valueData.synopsisImg.splice(index, 1);
    },
    async openTmap(v) {
      this.addressOptions.dialog = true;
    },
    // 应用总校的分类
    useCargey(val) {
      if (val) {
        getById({
          businessId: this.parentId,
        }).then((res) => {
          const data = res.data;
          this.schoolForm.valueData.categoryIds = data.categoryIds.split(",");
        });
      } else {
        this.schoolForm.valueData.categoryIds = [];
      }
    },
    // 省
    provinceChange(v) {
      this.schoolForm.valueData.province = this.addressOptions.province.find(
        (i) => i.value === this.schoolForm.province
      ).label;
      this.schoolForm.city = null;
      this.schoolForm.area = null;
      this.schoolForm.street = null;
      cityList({
        pid: v,
      }).then((res) => {
        this.addressOptions.city = res.data.map((i) => {
          return {
            label: i.cityName,
            value: i.cityCode,
            lat: i.lat,
            lng: i.lng,
          };
        });
      });
    },
    // 市
    cityChange(v) {
      this.schoolForm.valueData.city = this.addressOptions.city.find(
        (i) => i.value === this.schoolForm.city
      ).label;
      this.schoolForm.area = null;
      this.schoolForm.street = null;
      areaList({
        pid: v,
      }).then((res) => {
        this.addressOptions.area = res.data.map((i) => {
          return {
            label: i.areaName,
            value: i.areaCode,
            lat: i.lat,
            lng: i.lng,
          };
        });
      });
    },
    // 区
    areaChange(v) {
      this.schoolForm.valueData.region = this.addressOptions.area.find(
        (i) => i.value === this.schoolForm.area
      ).label;
      this.schoolForm.street = null;
      streetList({
        pid: v,
      }).then((res) => {
        this.addressOptions.street = res.data.map((i) => {
          return {
            label: i.streetName,
            value: i.streetCode,
            lat: i.lat,
            lng: i.lng,
          };
        });
      });
      const province = this.schoolForm.valueData.province;
      const city = this.schoolForm.valueData.city;
      const area = this.schoolForm.valueData.region;
      console.log(`${province}${city}${area}`);
      this.schoolForm.valueData.addressRemarks = `${province}${city}${area}`;
    },
    // 街道
    streetChange(v) {
      this.schoolForm.valueData.town = this.addressOptions.street.find(
        (i) => i.value === this.schoolForm.street
      ).label;
      const province = this.schoolForm.valueData.province;
      const city = this.schoolForm.valueData.city;
      const area = this.schoolForm.valueData.region;
      const street = this.schoolForm.valueData.town;
      this.schoolForm.valueData.addressRemarks = `${province}${city}${area}${street}`;
    },
    getData() {
      // 省
      provinceList().then((res) => {
        this.addressOptions.province = res.data.map((i) => {
          return {
            label: i.provinceName,
            value: i.provinceCode,
            lat: i.lat,
            lng: i.lng,
          };
        });
      });
      getAllLabels({
        status: 1,
        type: null,
      }).then((res) => {
        const data = res.data;
        data.forEach((i) => {
          i.label = i.name;
          i.value = i.id;
        });
        this.schoolForm.AllLabels = data;
      });
      // 获取课程分类
      getCategoryAll().then((res) => {
        this.categoryAllList = res.data;
      });
      // 查询机构详情
      getById({
        businessId: this.$route.query.id,
      }).then((res) => {
        const data = res.data;
        this.parentId = data.parentId || this.$store.getters.businessId;
        this.form.valueData = {
          name: data.name,
          logoImg: data.logoImg,
          synopsis: data.synopsis,
          foundTime: data.foundTime,
          serverPhone: data.serverPhone,
        };
        if (data.doBusinessTime) {
          this.weekData = JSON.parse(data.doBusinessTime);
        }
        const address = data.addressIds ? data.addressIds.split(",") : [];
        this.schoolForm.province = address[0] || "";
        this.schoolForm.city = address[1] || "";
        this.schoolForm.area = address[2] || "";
        this.schoolForm.street = address[3] || "";

        cityList({
          pid: address[0],
        }).then((res) => {
          this.addressOptions.city = res.data.map((i) => {
            return {
              label: i.cityName,
              value: i.cityCode,
              lat: i.lat,
              lng: i.lng,
            };
          });
        });
        areaList({
          pid: address[1],
        }).then((res) => {
          this.addressOptions.area = res.data.map((i) => {
            return {
              label: i.areaName,
              value: i.areaCode,
              lat: i.lat,
              lng: i.lng,
            };
          });
        });
        streetList({
          pid: address[2],
        }).then((res) => {
          this.addressOptions.street = res.data.map((i) => {
            return {
              label: i.streetName,
              value: i.streetCode,
              lat: i.lat,
              lng: i.lng,
            };
          });
        });
        const id = data.categoryIds ? data.categoryIds.split(",") : [];
        const name = data.categoryNames ? data.categoryNames.split(",") : [];
        // id.forEach((i, index) => {
        //   // const classify = this.schoolForm.childrenType.find(j => j.id == i).classify

        //   this.$nextTick(() => {
        //     // this.schoolForm.chooseTypes.push(`${i}:${name[index]}`)
        //     this.schoolForm.chooseTypes.push(`${i}:${name[index]}`)
        //   })
        // })
        const labels =
          data.backstageLabels && data.backstageLabels.length > 0
            ? data.backstageLabels.map((i) => {
                return i.id;
              })
            : [];
        this.schoolForm.valueData = {
          labels: labels,
          synopsisImg: data.synopsisImg ? data.synopsisImg.split(",") : [],
          categoryIds: id,
          categoryNames: name,
          detail: data.detail,
          province: data.province, // 省
          city: data.city, // 市
          region: data.region, // 区
          town: data.town, // 街道
          lat: data.lat,
          lng: data.lng,
          addressRemarks: data.addressRemarks,
        };
      });
    },
    addressDialog() {
      // this.initMap()
    },
    // 获取定位
    async getLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(this.showPosition);
      } else {
        this.$message({
          message: "获取不到你的位置信息",
          type: "warning",
        });
      }
      const options = { timeout: 1000 };
      const geolocation = new qq.maps.Geolocation(
        "R6GBZ-ZPH6S-F6XOL-6OEWC-VZNX2-GKFMY",
        "myapp"
      );
      geolocation.getLocation(
        (position) => {
          this.addressOptions.lat = position.lat;
          this.addressOptions.lng = position.lng;
        },
        (err) => {
          // console.log(err, '获取定位失败，重新获取中...')
          this.getLocation();
        },
        options
      );
    },
    showPosition(position) {},
    handleClickCategory(tab, event) {
      // console.log(tab.name, event, 'tab, event')
    },
    handleCheckAllChange(val) {
      const checkedCities = this.schoolForm.valueData.categoryIds;
      this.checkAll.forEach((i, index) => {
        if (i) {
          const arr = this.categoryAllList[index].categories.map((j) => {
            return j.id;
          });
          const set = new Set([...checkedCities, ...arr]);
          this.schoolForm.valueData.categoryIds = Array.from(set);
        } else {
          this.categoryAllList[index].categories.forEach((j) => {
            this.schoolForm.valueData.categoryIds.splice(
              this.categoryAllList[index].categories.indexOf(j.id),
              1
            );
          });
        }
      });
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {},
    submit() {
      // this.schoolForm.valueData.labels = this.schoolForm.valueData.labels.join(',')
      let form1 = false;
      let form2 = false;
      this.formRef.validate((valid) => {
        if (valid) {
          form1 = true;
        } else {
          return false;
        }
      });
      this.schoolFormFormRef.validate((valid) => {
        if (valid) {
          form2 = true;
        } else {
          return false;
        }
      });
      if (!form1 || !form2) {
        return this.$message.error("请完善学校信息");
      }
      const province = this.schoolForm.province;
      const city = this.schoolForm.city;
      const area = this.schoolForm.area;
      const street = this.schoolForm.street;
      const lat = this.schoolForm.valueData.lat;
      const lng = this.schoolForm.valueData.lng;
      if (!(province && city && area && lat && lng)) {
        return this.$message.error("请选择地址");
      }
      this.submitLoading = true;
      // 所有子分类
      const categoryArr = [];
      this.categoryAllList.forEach((i) => {
        categoryArr.push(...i.categories);
      });
      // 选中的子分类对象
      const same = categoryArr.filter((i) => {
        return this.schoolForm.valueData.categoryIds.indexOf(i.id) !== -1;
      });
      // 选中的子分类id
      const idsList = [];
      // 选中的子分类name
      const categoryNames = [];
      same.forEach((i) => {
        idsList.push(i.id);
        categoryNames.push(i.name);
      });
      // 选中的父分类id
      const parentIds = same.map((i) => {
        return i.parentId;
      });
      const categoryParentIds = Array.from(new Set(parentIds));
      const categoryParentNames = [];
      const classify = [];
      // 选中的父分类对象集合
      const parentObj = this.categoryAllList.filter((i) => {
        return categoryParentIds.indexOf(i.id) !== -1;
      });
      parentObj.forEach((i) => {
        categoryParentNames.push(i.name);
        classify.push(i.classify);
      });
      let type = null;
      const classifytype = [...new Set(classify)];
      const p = classifytype.reduce((prev, curr) => {
        return prev + curr;
      });
      switch (p) {
        case 1:
          type = 1;
          break;
        case 2:
          type = 2;
          break;
        case 3:
          type = 3;
          break;
      }
      const data = Object.assign(
        {},
        this.form.valueData,
        this.schoolForm.valueData
      );
      data.type = type;
      data.score="5";
      data.doBusinessTime = JSON.stringify(this.weekData);
      data.categoryParentIds = categoryParentIds.join(",");
      data.categoryParentNames = categoryParentNames.join(",");
      data.categoryIds = idsList.join(",");
      data.categoryNames = categoryNames.join(",");
      data.synopsisImg = data.synopsisImg.join(",");
      data.labels = data.labels ? data.labels.join(",") : [];
      data.id = this.$route.query.id;
      data.addressIds = `${province},${city},${area},${street || ""}`;
      updateById(data)
        .then((res) => {
          this.$message({
            message: "修改成功",
            type: "success",
          });
          this.$store.dispatch("tagsView/delView", this.$route);
          this.$router.push("/mechanism/school/list");
        })
        .finally(() => {
          this.submitLoading = false;
        });
    },
    closeEdit() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push("/mechanism/school/list");
    },
  },
};
</script>
<style lang="scss" scoped>
.content {
  // width: 100%;
}
.img-upload {
  cursor: pointer;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 5px;
  width: 187.5px;
  height: 140px;
  border: 1px dashed #6bb6fc;
  border-radius: 5px;
  .zt {
    z-index: 2;
    position: absolute;
    bottom: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 30px;
    color: #fff;
    background: rgba(0, 0, 0, 0.7);
  }
  i {
    font-size: 24px;
    color: #6bb6fc;
  }
  .el-image {
    cursor: pointer;
    width: 100%;
    height: 100%;
  }
  &:hover .img-upload-shaow {
    display: flex;
  }
  .img-upload-shaow {
    display: none;
    // display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    background: rgba(0, 0, 0, 0.3);
    // opacity: 0;
    > i {
      color: #fff;
    }
  }
}
/deep/.el-input--medium .el-input__inner {
  width: 40%;
}
/deep/.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  .el-input__inner {
    width: 220px;
  }
}
.disabled /deep/.el-upload--picture-card {
  display: none;
}
/deep/.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
/deep/.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
/deep/.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
/deep/.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
.searchAdress {
  margin-bottom: 10px;
  .el-select-dropdown__item {
    height: 70px;
  }
}
.disabled /deep/.el-upload {
  display: none;
}
// 截图
.vue-cropper {
  text-align: center;
}
</style>
